/**
 * <p>Title: SHAUtil</p>
 * <p>Description: 生成随机码和加密方法</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2016</p>
 * <p>Company: Baosight Software</p>
 * @author qianpengji
 * @version 1.0
 * <pre>Histroy:
 *       2016-10-10  qianpengji  Create
 *</pre>
*/
package cn.jhg.account.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Hex;

public class SHAUtil {

	/**
	 * 将byte数组转换为16进制输出
	 * @param bytes
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	public static String convertByteToHexString(String password) throws NoSuchAlgorithmException{
		MessageDigest md;// 加密初始化操作
		md = MessageDigest.getInstance("SHA-256");
		byte[] b = md.digest(password.getBytes());
		String output = Hex.encodeHexString(b);
//		String ret=Base64.encodeBase64String(b);
		return output;
	}
	
	/**
	 * 生成随机码
	 * @param length
	 * @return String
	 */
	 public static String getStringRandom(int length) {  
         
	        String val = "";  
	        Random random = new Random();  
	        String regExp = "^([0-9]+)|([A-Za-z]+)$";  //正则表达式，纯数字或者纯字母
	        Pattern pat = Pattern.compile(regExp); 
	        Boolean flag=true;
	        while(flag){
	        	//参数length，表示生成几位随机数  
	            for(int i = 0; i < length; i++) {     
	                String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
	                //输出字母还是数字  
	                if( "char".equalsIgnoreCase(charOrNum) ) {  
	                    //输出是大写字母还是小写字母  
	                    int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
	                    val += (char)(random.nextInt(26) + temp);  
	                } else if( "num".equalsIgnoreCase(charOrNum) ) {  
	                    val += String.valueOf(random.nextInt(10));  
	                }  
	            }  
	            Matcher mat = pat.matcher(val);
	            if(!mat.matches()){//只有当mat.matches()为false的时候能进来
	            	flag=false;
	            }else{
	            	val="";
	            }
	        }
	        return val;  
	    }
}
